<template>
  <div class="app-container">
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" label-width="auto" :inline="true">
        <el-form-item label="订单号" prop="orderId">
          <el-input style="width: 10px" v-model="queryParams.orderId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="抬头" prop="title">
          <el-input style="width: 10px" v-model="queryParams.title" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="发票id" prop="id">
          <el-input style="width: 10px" v-model="queryParams.id" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="渠道发票id" prop="channelInvoiceId">
          <el-input style="width: 10px" v-model="queryParams.channelInvoiceId" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="发票号码" prop="invoiceNo">
          <el-input style="width: 10px" v-model="queryParams.invoiceNo" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="平台" prop="platformId">
          <el-select clearable @keyup.enter="handleQuery" v-model="queryParams.platformId" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in platFormArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="渠道" prop="channelId">
          <el-select clearable @keyup.enter="handleQuery" v-model="queryParams.channelId" placeholder="请选择" style="width: 16rem">
            <el-option v-for="item in channelArr" :key="item.value" :label="item.label" :value="item.value" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select clearable @keyup.enter="handleQuery" v-model="queryParams.status" placeholder="请选择" style="width: 16rem">
            <el-option :value="0" label="待开票" />
            <el-option :value="1" label="开票中" />
            <el-option :value="2" label="开票成功" />
            <el-option :value="10" label="待作废" />
            <el-option :value="11" label="作废中" />
            <el-option :value="12" label="已作废" />
            <el-option :value="20" label="开票失败" />
          </el-select>
        </el-form-item>
        <el-form-item label="红票号码" prop="redNo">
          <el-input style="width: 10px" v-model="queryParams.redNo" placeholder="请输入" clearable @keyup.enter="handleQuery" />
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            style="width: 16rem"
            format="YYYY/MM/DD"
            value-format="YYYY-MM-DD"
            @change="handleCreateTimeChange"
            v-model="createTimes"
            type="daterange"
            range-separator="至"
            start-placeholder="开始时间"
            end-placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">
            <template #icon><Search /></template>
            搜索
          </el-button>
          <el-button @click="handleResetQuery">
            <template #icon><Refresh /></template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="never" class="table-container">
      <template #header>
        <el-button type="success" @click="handleOpenDialog('开票')">
          <template #icon><Plus /></template>
          开票
        </el-button>
        <el-button @click="handleExport" type="warning">
          <template #icon><Edit /></template>
          导出
        </el-button>
      </template>
      <el-table v-loading="loading" :data="TableData" highlight-current-row row-key="id" @row-click="handleRowClick">
        <el-table-column label="平台" min-width="80" align="center" prop="platformId">
          <template #default="scope">
            <div>{{ platFormEnum[scope.row.platformId] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="渠道" min-width="120" align="center" prop="channelId">
          <template #default="scope">
            <div>{{ channelEnum[scope.row.channelId] }}</div>
          </template>
        </el-table-column>
        <el-table-column label="抬头" min-width="280" align="center" prop="title">
          <template #default="scope">
            <el-popover placement="top-start" :width="200" trigger="hover">
              <div>
                <div style="margin-top: 6px">类型:{{ scope.row.type == 1 ? "个人" : "企业" }}</div>
                <div style="margin-top: 6px">税号:{{ scope.row.taxNo }}</div>
                <div style="margin-top: 6px">地址:{{ scope.row.address }}</div>
                <div style="margin-top: 6px">电话:{{ scope.row.phone }}</div>
                <div style="margin-top: 6px">开户银行:{{ scope.row.bank }}</div>
                <div style="margin-top: 6px">银行账号:{{ scope.row.bankAccount }}</div>
                <div style="margin-top: 6px">备注:{{ scope.row.remark }}</div>
              </div>
              <template #reference>
                <div style="color: #40a9ff; cursor: pointer">
                  {{ scope.row.title }}
                </div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="订单信息" min-width="120" align="center" prop="title">
          <template #default="scope">
            <el-popover v-if="scope.row.items" placement="top-start" :width="200" trigger="hover">
              <div v-for="(item, index) in scope.row.items" :key="index">
                <div style="margin-top: 6px">订单号:{{ item.orderId }}</div>
                <div style="margin-top: 6px">金额:{{ item.totalFee }}</div>
              </div>
              <template #reference>
                <div style="color: #40a9ff; cursor: pointer">订单信息</div>
              </template>
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="渠道发票id" min-width="120" align="center" prop="channelInvoiceId"></el-table-column>
        <el-table-column label="状态" min-width="80" align="center" prop="status">
          <template #default="scope">
            <div v-if="scope.row.status == 0">待开票</div>
            <div v-else-if="scope.row.status == 1">开票中</div>
            <div v-else-if="scope.row.status == 2">开票成功</div>
            <div v-else-if="scope.row.status == 10">待作废</div>
            <div v-else-if="scope.row.status == 11">作废中</div>
            <div v-else-if="scope.row.status == 12">已作废</div>
            <div v-else-if="scope.row.status == 20">开票失败</div>
          </template>
        </el-table-column>
        <el-table-column label="发票号" min-width="100" align="center" prop="invoiceNo"></el-table-column>
        <el-table-column label="发票地址" min-width="140" align="center" prop="status">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <div style="width: 100px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden">{{ scope.row.invoiceUrl }}</div>
              <CopyDocument v-if="scope.row.invoiceUrl" :size="3" color="blue" @click="handleCopy(scope.row.invoiceUrl)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="ofd地址" min-width="140" align="center" prop="invoiceOfdUrl">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <div style="width: 100px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden">{{ scope.row.invoiceOfdUrl }}</div>
              <CopyDocument v-if="scope.row.invoiceOfdUrl" :size="3" color="blue" @click="handleCopy(scope.row.invoiceOfdUrl)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="xml地址" min-width="140" align="center" prop="invoiceXmlUrl">
          <template #default="scope">
            <div style="display: flex; align-items: center; justify-content: center">
              <div style="width: 100px; white-space: nowrap; text-overflow: ellipsis; overflow: hidden">{{ scope.row.invoiceXmlUrl }}</div>
              <CopyDocument v-if="scope.row.invoiceXmlUrl" :size="3" color="blue" @click="handleCopy(scope.row.invoiceXmlUrl)" />
            </div>
          </template>
        </el-table-column>
        <el-table-column label="总金额" min-width="124" align="center" prop="totalFee"></el-table-column>
        <el-table-column label="金额不含税" min-width="124" align="center" prop="fee"></el-table-column>
        <el-table-column label="税额" min-width="124" align="center" prop="taxFee"></el-table-column>
        <el-table-column label="邮箱" min-width="124" align="center" prop="email"></el-table-column>
        <el-table-column label="创建时间" min-width="160" align="center" prop="createTime"></el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <div style="display: flex; justify-content: center; align-items: center">
              <el-button type="primary" link size="small" @click.stop="handleOpenDialog('重开', scope.row)">
                <template #icon><Pointer /></template>
                重开
              </el-button>
              <el-button type="danger" link size="small" @click.stop="handleRed(scope.row)">
                <template #icon><RemoveFilled /></template>
                红冲
              </el-button>
              <el-button type="success" link size="small" @click.stop="handleResend(scope.row)">
                <template #icon><Files /></template>
                重发
              </el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination v-if="total > 0" v-model:total="total" v-model:page="queryParams.pageNo" v-model:limit="queryParams.pageSize" @pagination="handleQuery" />
    </el-card>

    <Mymodel ref="modelRef" @success="handleSuccess" />
    <SendModal ref="sendRef" @success="handleSuccess" />
  </div>
</template>

<script setup lang="ts">
defineOptions({
  name: "SysMenu",
  inheritAttrs: false,
});

import OrderApi from "@/api/order";
import CommonApi from "@/api/common";
import Mymodel from "./components/Mymodel.vue";
import SendModal from "./components/sendModal.vue";
import ExportApi from "@/api/exports";

import { orderStatusEnum, platFormEnum, channelEnum, orderTypeEnum, bizTypeEnum, luggageEnum, channelArr, bizTypeArr, orderTypeArr, platFormArr, carTypeArr } from "@/enums/common";
import { MenuTypeEnum } from "@/enums/MenuTypeEnum";
const queryFormRef = ref(ElForm);
const total = ref(0);
const supplierOptions = ref();
const cityOptions = ref();
const createTimes = ref();
const modelRef = ref();
const sendRef = ref();

const loading = ref(false);

// 查询参数
const queryParams = reactive<MenuQuery>({
  pageNo: 1,
  pageSize: 10,
});
// 菜单表格数据
const TableData = ref([]);

// 选择表格的行菜单ID
const selectedMenuId = ref<number | undefined>();

//导出
function handleExport() {
  ExportApi.invoiceExport(queryParams).then((res) => {
    let data = res.data;
    ElMessage.success("导出完毕");
    if (!data) {
      return;
    }
    if (typeof window.navigator.msSaveBlob !== "undefined") {
      window.navigator.msSaveBlob(new Blob([data], { type: "application/vnd.ms-excel" }), fileName + ".xls");
    } else {
      let url = window.URL.createObjectURL(new Blob([data], { type: "application/vnd.ms-excel" }));
      let link = document.createElement("a");
      link.style.display = "none";
      link.href = url;
      link.setAttribute("download", "发票" + ".xlsx");
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link); //下载完成移除元素
      window.URL.revokeObjectURL(url); //释放掉blob对象
    }
  });
}
/**
 * 红冲
 */
function handleRed(row) {
  ElMessageBox.alert("确认红冲吗?", {
    showCancelButton: true,
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    callback: (action) => {
      if (action == "confirm") {
        OrderApi.redInvoice({ invoiceId: row.id }).then((res) => {
          if (res.code == 0) {
            ElMessage.success(res.message);
            handleQuery();
          }
        });
      }
    },
  });
}
//重开
function handleResend(row: any) {
  sendRef.value.edit(row);
  return;
}
/**重开 || 开票 */
function handleOpenDialog(title: any, row: any) {
  modelRef.value.edit(title, row);
}

function handleSuccess() {
  handleQuery();
}

function handleQuery() {
  loading.value = true;
  OrderApi.invoiceList(queryParams)
    .then((data) => {
      TableData.value = data.result;
      total.value = data.total * 1;
    })
    .finally(() => {
      loading.value = false;
    });
}
//复制发票地址
function handleCopy(url: string) {
  const textToCopy = url;
  // 创建一个新的 textarea 元素，设置其 value 为要复制的文本
  const textarea = document.createElement("textarea");
  textarea.value = textToCopy;
  document.body.appendChild(textarea);
  // 选中文本并复制
  textarea.select();
  document.execCommand("copy");
  // 移除 textarea 元素
  document.body.removeChild(textarea);
  ElMessage.success("复制成功");
}

function handleCreateTimeChange(time: any) {
  if (time) {
    queryParams.createTimeFrom = `${time[0]} 00:00:00`;
    queryParams.createTimeTo = `${time[1]} 23:59:59`;
  } else {
    queryParams.createTimeFrom = undefined;
    queryParams.createTimeTo = undefined;
  }
}

// 重置查询
function handleResetQuery() {
  queryParams.createTimeFrom = undefined;
  queryParams.createTimeTo = undefined;
  createTimes.value = null;

  queryFormRef.value.resetFields();
  queryParams.pageNo = 1;
  handleQuery();
}

// 行点击事件
function handleRowClick(row: MenuVO) {
  // 记录表格选择的菜单ID，新增子菜单作为父菜单ID
  selectedMenuId.value = row.id;
}

onMounted(() => {
  handleQuery();
  CommonApi.getSupplier({ pageNo: 1, pageSize: 9999, status: 1 }).then((data) => {
    if (data.code == 0) {
      supplierOptions.value = data.result;
    }
  });
  CommonApi.getCity({ pageNo: 1, pageSize: 9999 }).then((data) => {
    if (data.code == 0) {
      cityOptions.value = data.result;
    }
  });
});
</script>
<style lang="scss" scoped>
.red_rate {
  color: red;
}
.address_box {
  display: flex;
  flex-direction: column;
  align-items: left;
  justify-content: left;
  .item {
    display: flex;
    align-items: center;
    margin: 4px 0;
    .tag {
      width: 50px;
      height: 23px;
      text-align: center;
      color: orange;
      background: #fff8e6;
    }
    .tag2 {
      color: #3fd175;
      background: #e7faf0;
    }
  }
}
</style>
